package com.google.code.rgbgoesbetween.gui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.code.rgbgoesbetween.GlobalConstants;
import com.google.code.rgbgoesbetween.R;
import com.google.code.rgbgoesbetween.data.AccountStatus;
import com.google.code.rgbgoesbetween.data.Profile;
import com.google.code.rgbgoesbetween.data.QueryStatus;
import com.google.code.rgbgoesbetween.services.DataProvider;
import com.google.code.rgbgoesbetween.services.SessionManager;
/**
 * Displays the home screen for the user of the app
 * @author Avanyali
 *
 */
public class HomeActivity extends Activity implements OnClickListener {

	private Button reportButton;
	private Button listItemsButton;
	private Button adminUnlockAccountButton;
	private Button adminLockAccountButton;
	private Button adminCreateAdminAccountButton;
	private Button adminDeleteUserAccountButton;
	private Button searchButton;

	/**
	 * Displays the various option buttons that the user has access to,
	 * displays extra buttons for admins
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e("HomeActivity", "onCreate");
		if (isAdmin()) {
			Log.e("HomeActivity", "We got an admin!!!");
			setContentView(R.layout.activity_admin_home);
			adminUnlockAccountButton = (Button) findViewById(R.id.admin_view_unlock_button);
			adminUnlockAccountButton.setOnClickListener(this);
			adminCreateAdminAccountButton = (Button) findViewById(R.id.admin_view_create_admin_button);
			adminCreateAdminAccountButton.setOnClickListener(this);
			adminLockAccountButton = (Button) findViewById(R.id.admin_view_lock_button);
			adminLockAccountButton.setOnClickListener(this);
			adminDeleteUserAccountButton = (Button) findViewById(R.id.admin_view_remove_users_button);
			adminDeleteUserAccountButton.setOnClickListener(this);
		} else {
			setContentView(R.layout.activity_home);
		}
		SessionManager.getSessionManager().init();
		DataProvider.getDataProvider().init(this);

		TextView usernameText = (TextView) findViewById(R.id.home_user_txt);
		String username = SessionManager.getSessionManager()
				.getCurrentUsername();
		if (username == null) {
			Toast.makeText(this, "Sorry, no one is logged in!",
					Toast.LENGTH_LONG).show();
			this.finish();
		} else {
			String hello = this.getResources().getString(
					R.string.home_username_string);
			usernameText.setText(hello + " " + username);
		}

		reportButton = (Button) findViewById(R.id.home_report_button);
		listItemsButton = (Button) findViewById(R.id.home_view_items_button);
		searchButton = (Button) findViewById(R.id.home_search_btn);
		reportButton.setOnClickListener(this);
		listItemsButton.setOnClickListener(this);
		searchButton.setOnClickListener(this);
	}

	private boolean isAdmin() {
		return AccountStatus.ADMIN_MEMBER.equals(SessionManager
				.getSessionManager().getProfile().getAccountStatus());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_home, menu);
		return true;
	}

	/**
	 * Switches screens to other activities based on which button the user
	 * clicks. These include registration, report items, listing user items, 
	 * advanced searching. In addition, it handles admin functionality.
	 */
	@Override
	public void onClick(View v) {
		if (v == null) {
			return;
		}
		if (v == reportButton) {
			Intent i = new Intent(this, ReportItemActivity.class);
			this.startActivity(i);
		} else if (v == listItemsButton) {
			Intent i = new Intent(this, ItemListDisplayActivity.class);
			i.putExtra(GlobalConstants.FROM_HOME, true);
			this.startActivity(i);
		} else if (v == adminUnlockAccountButton) {
			Log.d("HOME_ACTIVITY", "onClick() in adminUnlockAccountButton");
			unlockAccount();
		} else if (v == adminLockAccountButton) {
			Log.d("HOME_ACTIVITY", "onClick() in adminLockAccountButton");
			lockAccount();
		} else if (v == adminCreateAdminAccountButton) {
			createAdmin();
		} else if (v == adminDeleteUserAccountButton) {
			deleteAccount();
		} else if (v == searchButton) {
			Intent i = new Intent(this, AdvancedSearchActivity.class);
			startActivity(i);
		}else {
			throw new RuntimeException();
		}
	}

	/**
	 * Creates a new admin with a new name and password
	 */
	private void createAdmin() {
		View dialogLayout = getLayoutInflater().inflate(
				R.layout.admin_create_user_dialog, null);
		Button finishButton = (Button) dialogLayout
				.findViewById(R.id.admin_register_button);
		final TextView notificationsView = (TextView) dialogLayout
				.findViewById(R.id.admin_notifications_field);
		final EditText usernameView = (EditText) dialogLayout
				.findViewById(R.id.admin_username_register_field);
		final EditText passwordView = (EditText) dialogLayout
				.findViewById(R.id.admin_password_register_field);
		final EditText passwordConfirmView = (EditText) dialogLayout
				.findViewById(R.id.admin_password_register_confirm_field);
		final AlertDialog dialog = new AlertDialog.Builder(this).setView(
				dialogLayout).create();

		finishButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (v.getId() == R.id.admin_register_button) {
					if (!passwordView.getText().toString()
							.equals(passwordConfirmView.getText().toString())) {
						notificationsView
								.setText("Your passwords do not match. Please try again.");
						return;
					}
					String username = usernameView.getText().toString()
							.toLowerCase();
					String password = passwordView.getText().toString();
					AccountStatus status = SessionManager.getSessionManager()
							.createAdminProfile(username, password);
					Log.e("User registration", String.format(
							"username: %s password: %s status: %s", username,
							password, status.toString()));
					if (AccountStatus.STANDARD_MEMBER.equals(status)
							|| AccountStatus.ADMIN_MEMBER.equals(status)) {
						notificationsView.setText("");
						Toast.makeText(HomeActivity.this,
								"Admin created successfully.",
								Toast.LENGTH_LONG).show();
						dialog.dismiss();
					} else {
						notificationsView
								.setText("That username has been taken. Please select another.");
					}
				}
			}
		});

		dialog.show();
	}

	/**
	 * Unlocks a user account from the admin HomeActivity
	 * Does not unlock accounts that do not exist or have been deleted
	 */
	private void unlockAccount() {
		View view = getLayoutInflater().inflate(R.layout.admin_unlock_dialog,
				null);
		Button btn = (Button) view.findViewById(R.id.admin_unlock_ok);
		final EditText et = (EditText) view
				.findViewById(R.id.admin_unlock_input_name);
		final AlertDialog dialog = new AlertDialog.Builder(this).setView(view)
				.create();
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Profile acct = DataProvider.getDataProvider().getProfile(
						et.getText().toString());
				if (acct == null || acct.getAccountStatus() == AccountStatus.MEMBER_DELETED) {
					Toast.makeText(HomeActivity.this, "Account does not exist",
							Toast.LENGTH_LONG).show();
					dialog.dismiss();
					return;
				}
				acct.setAccountStatus(AccountStatus.STANDARD_MEMBER);
				QueryStatus qs = DataProvider.getDataProvider().updateProfile(
						acct);
				if (!QueryStatus.QUERY_SUCCESS.equals(qs)) {
					Toast.makeText(HomeActivity.this, "Account unlock failed",
							Toast.LENGTH_LONG).show();
					dialog.dismiss();
				}
				SessionManager.getSessionManager().clearInvalidTries(
						acct.getUsername());
				Toast.makeText(HomeActivity.this, "Account unlock successful",
						Toast.LENGTH_LONG).show();
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	/**
	 * Sets the status of an account to deleted, disabling the creation of an
	 * account of the same name. Can only delete existing accounts.
	 */
	private void deleteAccount() {
		View view = getLayoutInflater().inflate(R.layout.admin_delete_dialog,
				null);
		Button btn = (Button) view.findViewById(R.id.admin_delete_ok);
		final EditText et = (EditText) view
				.findViewById(R.id.admin_delete_input_name);
		final AlertDialog dialog = new AlertDialog.Builder(this).setView(view)
				.create();
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Profile acct = DataProvider.getDataProvider().getProfile(
						et.getText().toString());
				if (acct == null || acct.getAccountStatus() == AccountStatus.MEMBER_DELETED) {
					Toast.makeText(HomeActivity.this, "Account does not exist",
							Toast.LENGTH_LONG).show();
					dialog.dismiss();
					return;
				}
				QueryStatus qs = DataProvider.getDataProvider().deleteProfile(
						acct);
				if (!QueryStatus.QUERY_SUCCESS.equals(qs)) {
					Toast.makeText(HomeActivity.this, "Account delete failed",
							Toast.LENGTH_LONG).show();
					dialog.dismiss();
				}
				Toast.makeText(HomeActivity.this, "Account delete successful",
						Toast.LENGTH_LONG).show();
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	/**
	 * Locks the account of a user based on the name entered in the dialog box. Can
	 * only lock accounts that exist.
	 */
	private void lockAccount() {
		View view = getLayoutInflater().inflate(R.layout.admin_lock_dialog,
				null);
		Button btn = (Button) view.findViewById(R.id.admin_lock_ok);
		final EditText et = (EditText) view
				.findViewById(R.id.admin_lock_input_name);
		final AlertDialog dialog = new AlertDialog.Builder(this).setView(view)
				.create();
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Profile acct = DataProvider.getDataProvider().getProfile(
						et.getText().toString());
				if (acct != null && acct.getAccountStatus() != AccountStatus.MEMBER_DELETED) {
					acct.setAccountStatus(AccountStatus.LOCKED_MEMBER);
					DataProvider.getDataProvider().updateProfile(acct);
					Toast.makeText(HomeActivity.this, "Account Locked",
							Toast.LENGTH_LONG).show();
					dialog.dismiss();
				} else {
					Toast.makeText(HomeActivity.this, "Account does not exist",
							Toast.LENGTH_LONG).show();
					dialog.dismiss();
					return;
				}
				dialog.dismiss();
			}

		});
		dialog.show();
	}
}
